package com.gordon.test1.RecycleViewRefresh;

import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.gordon.test1.R;


/**
 * Created by Administrator on 2016/2/22.
 */
public class LoadMoreRecyclerView extends RecyclerView {

    public final static int TYPE_NORMAL = 0;
    /**头部--支持头部增加一个headerView*/
    public final static int TYPE_HEADER = 1;
    /**底部--一般都是loading_more */
    public final static int TYPE_FOOTER = 2;
    /**表示item以list模式展示*/
    public final static int TYPE_LIST = 3;
    /**表示item以网格模式展示*/
    public final static int TYPE_STAGGER = 4;
    /**是否允许加载更多*/
    private boolean mIsFooterEnable = false;
    /**标记是否正在加载更多，防止再次调用加载更多接口*/
    private boolean mIsLoadingMore;
    /**自定义实现了头部和底部加载更多的adapter*/
    private AutoLoadAdapter mAutoLoadAdapter;
    /**标记加载更多的view在整个RecyclerView中的位置position*/
    private int mLoadMorePosition;
    /**标记自动加载更多，true表示剩下4个item时就自动加载，false表示最后一个出来时才自动加载，默认为false*/
    private boolean mAutoLoadMore;
    /**加载更多的监听*/
    private LoadMoreListener mListener;
    /**设置加载更多的监听*/
    public void setLoadMoreListener(LoadMoreListener listener){
        this.mListener = listener;
    }

    public interface LoadMoreListener{
        void onLoadMore();
    }

    public LoadMoreRecyclerView(Context context) {
        this(context, null);
    }

    public LoadMoreRecyclerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadMoreRecyclerView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    /**初始化滑动监听，在此做加载更多操作*/
    private void init() {
        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mListener != null && mIsFooterEnable && !mIsLoadingMore && dy > 0) {
                    int lastVisiblePosition = getLastVisiblePosition();
                    if(!mAutoLoadMore) {
                        if (lastVisiblePosition + 1 == mAutoLoadAdapter.getItemCount()) {
                            setLoadingMore(true);
                            mLoadMorePosition = lastVisiblePosition;
                            mListener.onLoadMore();
                        }
                    }else{
                        if(lastVisiblePosition >= mAutoLoadAdapter.getItemCount() - 4){
                            setLoadingMore(true);
                            mLoadMorePosition = lastVisiblePosition;
                            mListener.onLoadMore();
                        }
                    }
                }
            }
        });
    }
    /**
     * recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            int lastVisibleItem = ((LinearLayoutManager) mLayoutManager).findLastVisibleItemPosition();
            int totalItemCount = mLayoutManager.getItemCount();
            //lastVisibleItem >= totalItemCount - 4 表示剩下4个item自动加载，各位自由选择
            // dy>0 表示向下滑动
            if (lastVisibleItem >= totalItemCount - 4 && dy > 0) {
            if(isLoadingMore){
                Log.d(TAG,"ignore manually update!");
            } else{
                loadPage();//这里多线程也要手动控制isLoadingMore
                isLoadingMore = false;
            }
            }
            }
    });
   */

    public void setmAutoLoadMore(boolean autoLoadMore){
        mAutoLoadMore = autoLoadMore;
    }

    /**获取最后一条item展示的位置*/
    private int getLastVisiblePosition() {
        int position;
        if (getLayoutManager() instanceof LinearLayoutManager) {
            position = ((LinearLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
        } else if (getLayoutManager() instanceof GridLayoutManager) {
            position = ((GridLayoutManager) getLayoutManager()).findLastVisibleItemPosition();
        } else if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getLayoutManager();
            int[] lastPositions = layoutManager.findLastVisibleItemPositions(new int[layoutManager.getSpanCount()]);
            position = getMaxPosition(lastPositions);
        } else {
            position = getLayoutManager().getItemCount() - 1;
        }
        return position;
    }

    /**获得最大的位置*/
    private int getMaxPosition(int[] positions) {
        int size = positions.length;
        int maxPosition = Integer.MIN_VALUE;
        for(int i = 0; i < size ; i++){
            maxPosition = Math.max(maxPosition,positions[i]);
        }
        return maxPosition;
    }

    /**设置正在加载更多的标志*/
    public void setLoadingMore(boolean loadingMore) {
        this.mIsLoadingMore = loadingMore;
    }

    /**自定义实现了头部和底部加载更多的adapter*/
    public class AutoLoadAdapter extends Adapter<ViewHolder>{
        /**数据adapter*/
        private Adapter mInternalAdapter;
        private boolean mHeaderEnable;
        private int mHeaderResId;

        public AutoLoadAdapter(Adapter adapter){
            mInternalAdapter = adapter;
            mHeaderEnable = false;
        }

        @Override
        public int getItemViewType(int position) {
            int headerPosition = 0;
            int footerPosition = getItemCount() - 1;
            if(headerPosition == position && mHeaderEnable && mHeaderResId > 0){
                return TYPE_HEADER;
            }
            if(footerPosition == position && mIsFooterEnable){
                return TYPE_FOOTER;
            }
            /**
             * 这么做保证layoutManager切换之后能及时的刷新上对的布局
             */
            if(getLayoutManager() instanceof LinearLayoutManager){
                return TYPE_LIST;
            }else if(getLayoutManager() instanceof StaggeredGridLayoutManager){
                return TYPE_STAGGER;
            }else{
                return TYPE_NORMAL;
            }

        }

        /**需要计算头部和底部的两个*/
        @Override
        public int getItemCount() {
            int count = mInternalAdapter.getItemCount();
            if(mHeaderEnable) count++;
            if(mIsFooterEnable) count++;
            return count;
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
           if(viewType == TYPE_HEADER){
               return new HeaderViewHolder(LayoutInflater.from(parent.getContext())
                       .inflate(mHeaderResId, parent, false));
           }
           if(viewType == TYPE_FOOTER){
               return new FooterViewHolder(LayoutInflater.from(parent.getContext())
                       .inflate(R.layout.recycleview_footerview, parent, false));
           }else{
               return mInternalAdapter.onCreateViewHolder(parent,viewType);
           }
        }

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            int type = getItemViewType(position);
            if(type != TYPE_FOOTER && type != TYPE_HEADER){
                mInternalAdapter.onBindViewHolder(holder,position);
            }
        }

        public class HeaderViewHolder extends ViewHolder{

            public HeaderViewHolder(View itemView) {
                super(itemView);
            }
        }

        public class FooterViewHolder extends ViewHolder{

            public FooterViewHolder(View itemView) {
                super(itemView);
            }
        }

        public void addHeaderView(int resId){
            mHeaderResId = resId;
        }

        public void setHeaderEnable(boolean enable){
            mHeaderEnable = enable;
        }
    }

    @Override
    public void setAdapter(Adapter adapter) {
        if(adapter != null){
            mAutoLoadAdapter = new AutoLoadAdapter(adapter);
        }
        super.swapAdapter(mAutoLoadAdapter,true);
    }

    /**
     * 切换layoutManager
     *
     * 为了保证切换之后页面上还是停留在当前展示的位置，记录下切换之前的第一条展示位置，切换完成之后滚动到该位置
     * 另外切换之后必须要重新刷新下当前已经缓存的itemView，否则会出现布局错乱（俩种模式下的item布局不同），
     * RecyclerView提供了swapAdapter来进行切换adapter并清理老的itemView cache
     *
     * @param layoutManager
     */
    public void switchLayoutManager(LayoutManager layoutManager) {
        int firstVisiblePosition = getFirstVisiblePosition();
//        getLayoutManager().removeAllViews();
        setLayoutManager(layoutManager);
//        super.swapAdapter(mAutoLoadAdapter, true);
        getLayoutManager().scrollToPosition(firstVisiblePosition);
    }

    /**获取第一个item的位置*/
    private int getFirstVisiblePosition() {
        int position;
        if (getLayoutManager() instanceof LinearLayoutManager) {
            position = ((LinearLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
        } else if (getLayoutManager() instanceof GridLayoutManager) {
            position = ((GridLayoutManager) getLayoutManager()).findFirstVisibleItemPosition();
        } else if (getLayoutManager() instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) getLayoutManager();
            int[] lastPositions = layoutManager.findFirstVisibleItemPositions(new int[layoutManager.getSpanCount()]);
            position = getMinPositions(lastPositions);
        } else {
            position = 0;
        }
        return position;
    }

    /**
     * 获得当前展示最小的position
     *
     * @param positions
     * @return
     */
    private int getMinPositions(int[] positions) {
        int size = positions.length;
        int minPosition = Integer.MAX_VALUE;
        for (int i = 0; i < size; i++) {
            minPosition = Math.min(minPosition, positions[i]);
        }
        return minPosition;
    }

    /**添加头部view*/
    public void addHeaderView(int resId){
        mAutoLoadAdapter.addHeaderView(resId);
    }

    /**设置头部是否展示*/
    public void setHeaderEnable(boolean enable){
        mAutoLoadAdapter.setHeaderEnable(enable);
    }
    /**设置是否支持滑动到最后一条时自动加载更多，没有更多数据时要设为false*/
    public void setLoadMoreEnable(boolean loadMore){
        mIsFooterEnable = loadMore;
    }

    /**
     * 通知更多的数据已经加载
     *
     * 每次加载完成之后添加了Data数据，用notifyItemRemoved来刷新列表展示，
     * 而不是用notifyDataSetChanged来刷新列表
     *
     * @param hasMore
     */
    public void notityMoreFinish(boolean hasMore){
        setLoadMoreEnable(hasMore);
        // 移除footerview
        getAdapter().notifyItemRemoved(mLoadMorePosition);
        mIsLoadingMore = false;
    }

}
